Coverage Report

Created: 2026-11-19 22:35

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
D:\a\cssh-rs\cssh-rs\cssh-rs-platform-windows\src\api.rs
Line
Count
Source
1
//! Windows API abstraction layer for console and system operations.
2
//!
3
//! This module provides a trait-based abstraction over Windows APIs to enable
4
//! mocking in tests and centralize Windows-specific functionality.
5
6
use log::{error, warn};
7
use std::ffi::{OsStr, OsString};
8
use std::os::windows::ffi::OsStrExt;
9
use std::{mem, ptr};
10
11
use windows::core::{BOOL, HSTRING, PCWSTR};
12
use windows::Win32::Foundation::{COLORREF, FALSE, HANDLE, HWND, LPARAM, TRUE};
13
use windows::Win32::Graphics::Dwm::{DwmSetWindowAttribute, DWMWA_BORDER_COLOR};
14
use windows::Win32::Graphics::Gdi::InvalidateRect;
15
use windows::Win32::System::Console::{
16
    FillConsoleOutputAttribute, GetConsoleProcessList, GetConsoleScreenBufferInfo,
17
    GetConsoleScreenBufferInfoEx, GetConsoleWindow, GetStdHandle, ReadConsoleInputW,
18
    ReadConsoleOutputAttribute, SetConsoleCtrlHandler, SetConsoleScreenBufferInfoEx,
19
    SetConsoleTextAttribute, WriteConsoleOutputAttribute, CONSOLE_CHARACTER_ATTRIBUTES,
20
    CONSOLE_SCREEN_BUFFER_INFO, CONSOLE_SCREEN_BUFFER_INFOEX, COORD, CTRL_BREAK_EVENT,
21
    CTRL_C_EVENT, INPUT_RECORD, INPUT_RECORD_0, STD_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
22
};
23
use windows::Win32::System::Console::{GetConsoleMode, SetConsoleMode, CONSOLE_MODE};
24
use windows::Win32::System::Console::{
25
    ScrollConsoleScreenBufferW, SetConsoleCursorPosition, CHAR_INFO, KEY_EVENT as KEY_EVENT_U32,
26
    SMALL_RECT,
27
};
28
use windows::Win32::System::Threading::PROCESS_ACCESS_RIGHTS;
29
use windows::Win32::System::Threading::{
30
    CreateProcessW, CREATE_NEW_CONSOLE, PROCESS_INFORMATION, STARTF_USESHOWWINDOW, STARTUPINFOW,
31
};
32
use windows::Win32::System::Threading::{GetExitCodeProcess, OpenProcess};
33
use windows::Win32::UI::WindowsAndMessaging::{
34
    BringWindowToTop, EnumWindows, GetForegroundWindow, GetWindowPlacement, GetWindowTextW,
35
    GetWindowThreadProcessId, MoveWindow, SetWindowPos, SetWindowTextW, ShowWindow, HWND_NOTOPMOST,
36
    HWND_TOPMOST, SHOW_WINDOW_CMD, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, SW_SHOWNOACTIVATE,
37
    SYSTEM_METRICS_INDEX, WINDOWPLACEMENT,
38
};
39
40
#[cfg(any(test, feature = "mock"))]
41
use mockall::automock;
42
43
use crate::MAX_WINDOW_TITLE_LENGTH;
44
45
/// Trait for Windows API operations to enable mocking in tests.
46
///
47
/// This trait abstracts Windows API calls to allow for unit testing without
48
/// actual system interaction. All console and system operations should go
49
/// through this trait.
50
#[cfg_attr(any(test, feature = "mock"), automock)]
51
pub trait WindowsApi: Send + Sync {
52
    /// Sets the console window title.
53
    ///
54
    /// # Arguments
55
    ///
56
    /// * `title` - The string to be set as window title
57
    ///
58
    /// # Returns
59
    ///
60
    /// Result indicating success or failure of the operation
61
    fn set_console_title(&self, title: &str) -> windows::core::Result<()>;
62
63
    /// Gets the console window title as UTF-16 buffer.
64
    ///
65
    /// # Arguments
66
    ///
67
    /// * `buffer` - Mutable buffer to store the UTF-16 encoded title
68
    ///
69
    /// # Returns
70
    ///
71
    /// Number of characters copied to the buffer
72
    fn get_console_title(&self, buffer: &mut [u16]) -> i32;
73
74
    /// Gets OS version string.
75
    ///
76
    /// # Returns
77
    ///
78
    /// String representation of the OS version
79
    fn get_os_version(&self) -> String;
80
81
    /// Arranges the console window position and size.
82
    ///
83
    /// # Arguments
84
    ///
85
    /// * `x` - The x coordinate to move the window to
86
    /// * `y` - The y coordinate to move the window to
87
    /// * `width` - The width in pixels to resize the window to
88
    /// * `height` - The height in pixels to resize the window to
89
    ///
90
    /// # Returns
91
    ///
92
    /// Result indicating success or failure of the operation
93
    fn arrange_console(&self, x: i32, y: i32, width: i32, height: i32)
94
        -> windows::core::Result<()>;
95
96
    /// Sets console text attribute.
97
    ///
98
    /// # Arguments
99
    ///
100
    /// * `attributes` - Console character attributes to set
101
    ///
102
    /// # Returns
103
    ///
104
    /// Result indicating success or failure of the operation
105
    fn set_console_text_attribute(
106
        &self,
107
        attributes: CONSOLE_CHARACTER_ATTRIBUTES,
108
    ) -> windows::core::Result<()>;
109
110
    /// Gets console screen buffer info.
111
    ///
112
    /// # Returns
113
    ///
114
    /// Console screen buffer information or error
115
    fn get_console_screen_buffer_info(&self) -> windows::core::Result<CONSOLE_SCREEN_BUFFER_INFO>;
116
117
    /// Fills console output with specified attribute.
118
    ///
119
    /// # Arguments
120
    ///
121
    /// * `attribute` - Attribute to fill with
122
    /// * `length` - Number of characters to fill
123
    /// * `coord` - Starting coordinate
124
    ///
125
    /// # Returns
126
    ///
127
    /// Number of characters actually filled or error
128
    fn fill_console_output_attribute(
129
        &self,
130
        attribute: u16,
131
        length: u32,
132
        coord: COORD,
133
    ) -> windows::core::Result<u32>;
134
135
    /// Reads a run of per-cell attributes from the console screen buffer.
136
    ///
137
    /// # Arguments
138
    ///
139
    /// * `length` - Number of cells to read.
140
    /// * `coord` - Starting coordinate.
141
    ///
142
    /// # Returns
143
    ///
144
    /// The attributes read (one per cell) or error.
145
    fn read_console_output_attribute(
146
        &self,
147
        length: u32,
148
        coord: COORD,
149
    ) -> windows::core::Result<Vec<u16>>;
150
151
    /// Writes a run of per-cell attributes to the console screen buffer.
152
    ///
153
    /// # Arguments
154
    ///
155
    /// * `attributes` - Attributes to write (one per cell).
156
    /// * `coord` - Starting coordinate.
157
    ///
158
    /// # Returns
159
    ///
160
    /// Number of cells actually written or error.
161
    fn write_console_output_attribute(
162
        &self,
163
        attributes: &[u16],
164
        coord: COORD,
165
    ) -> windows::core::Result<u32>;
166
167
    /// Reads the extended console screen buffer info, including the 16-entry
168
    /// RGB color palette.
169
    ///
170
    /// # Returns
171
    ///
172
    /// The [`CONSOLE_SCREEN_BUFFER_INFOEX`] for the output buffer or error.
173
    fn get_console_screen_buffer_info_ex(
174
        &self,
175
    ) -> windows::core::Result<CONSOLE_SCREEN_BUFFER_INFOEX>;
176
177
    /// Writes the extended console screen buffer info, including the 16-entry
178
    /// RGB color palette.
179
    ///
180
    /// # Arguments
181
    ///
182
    /// * `info` - The [`CONSOLE_SCREEN_BUFFER_INFOEX`] to apply.
183
    ///
184
    /// # Returns
185
    ///
186
    /// Result indicating success or failure of the operation.
187
    fn set_console_screen_buffer_info_ex(
188
        &self,
189
        info: &CONSOLE_SCREEN_BUFFER_INFOEX,
190
    ) -> windows::core::Result<()>;
191
192
    /// Scrolls console screen buffer.
193
    ///
194
    /// # Arguments
195
    ///
196
    /// * `scroll_rect` - Rectangle to scroll
197
    /// * `scroll_target` - Target coordinate for scrolling
198
    /// * `fill_char` - Character to fill empty space with
199
    ///
200
    /// # Returns
201
    ///
202
    /// Result indicating success or failure of the operation
203
    fn scroll_console_screen_buffer(
204
        &self,
205
        scroll_rect: SMALL_RECT,
206
        scroll_target: COORD,
207
        fill_char: CHAR_INFO,
208
    ) -> windows::core::Result<()>;
209
210
    /// Sets console cursor position.
211
    ///
212
    /// # Arguments
213
    ///
214
    /// * `position` - New cursor position
215
    ///
216
    /// # Returns
217
    ///
218
    /// Result indicating success or failure of the operation
219
    fn set_console_cursor_position(&self, position: COORD) -> windows::core::Result<()>;
220
221
    /// Gets standard handle.
222
    ///
223
    /// # Arguments
224
    ///
225
    /// * `handle_type` - Type of standard handle to retrieve
226
    ///
227
    /// # Returns
228
    ///
229
    /// Handle to the requested standard device or error
230
    fn get_std_handle(&self, handle_type: STD_HANDLE) -> windows::core::Result<HANDLE>;
231
232
    /// Reads console input.
233
    ///
234
    /// # Arguments
235
    ///
236
    /// * `buffer` - Buffer to store input records
237
    ///
238
    /// # Returns
239
    ///
240
    /// Number of records read or error
241
    fn read_console_input(&self, buffer: &mut [INPUT_RECORD]) -> windows::core::Result<u32>;
242
243
    /// Sets DWM window attribute for border color.
244
    ///
245
    /// # Arguments
246
    ///
247
    /// * `color` - Color to set as border color
248
    ///
249
    /// # Returns
250
    ///
251
    /// Result indicating success or failure of the operation
252
    fn set_console_border_color(&self, color: &COLORREF) -> windows::core::Result<()>;
253
254
    /// Marks the entire console window client area as needing a redraw.
255
    ///
256
    /// Used to nudge the legacy Win10 conhost into repainting from its
257
    /// own buffer state after bulk attribute changes that the renderer
258
    /// otherwise leaves stale on the trailing row/column.
259
    ///
260
    /// # Returns
261
    ///
262
    /// Result indicating success or failure of the operation
263
    fn invalidate_console_window(&self) -> windows::core::Result<()>;
264
265
    /// Writes input records to the console input buffer.
266
    ///
267
    /// # Arguments
268
    ///
269
    /// * `buffer` - Input records to write
270
    /// * `number_written` - Mutable reference to store number of records written
271
    ///
272
    /// # Returns
273
    ///
274
    /// Result indicating success or failure of the operation
275
    fn write_console_input(
276
        &self,
277
        buffer: &[INPUT_RECORD],
278
        number_written: &mut u32,
279
    ) -> windows::core::Result<()>;
280
281
    /// Gets the last Windows error code.
282
    ///
283
    /// # Returns
284
    ///
285
    /// The last error code from Windows API
286
    fn get_last_error(&self) -> u32;
287
288
    /// Interrupt every process attached to the caller's console.
289
    ///
290
    /// Sends `CTRL_C_EVENT` to process group 0 so a Ctrl+C relayed from the
291
    /// daemon reaches the child exactly as a focused Ctrl+C would.
292
    /// `CTRL_BREAK_EVENT` is not interchangeable: many programs treat only
293
    /// Ctrl+C as the interrupt (e.g. `ping` stops on Ctrl+C but merely prints
294
    /// statistics on Ctrl+Break). The caller shields itself with the handler
295
    /// from [`Self::install_console_ctrl_handler`], since group 0 signals it too.
296
    /// <https://learn.microsoft.com/en-us/windows/console/generateconsolectrlevent>
297
    ///
298
    /// # Returns
299
    ///
300
    /// Result indicating success or failure of the operation
301
    fn interrupt_console_process_group(&self) -> windows::core::Result<()>;
302
303
    /// Send a console control event to a process group.
304
    /// <https://learn.microsoft.com/en-us/windows/console/generateconsolectrlevent>
305
    ///
306
    /// # Arguments
307
    ///
308
    /// * `ctrl_event`       - `CTRL_C_EVENT` or `CTRL_BREAK_EVENT`.
309
    /// * `process_group_id` - Process id of the group leader.
310
    ///
311
    /// # Returns
312
    ///
313
    /// Result indicating success or failure of the operation
314
    fn generate_console_ctrl_event(
315
        &self,
316
        ctrl_event: u32,
317
        process_group_id: u32,
318
    ) -> windows::core::Result<()>;
319
320
    /// Install a console control handler that shields this process from
321
    /// CTRL+C and CTRL+Break.
322
    ///
323
    /// The handler reports both `CTRL_C_EVENT` and `CTRL_BREAK_EVENT` as
324
    /// handled, so neither user-typed nor group-relayed signals terminate the
325
    /// calling process; other control events keep their default handling.
326
    ///
327
    /// # Returns
328
    ///
329
    /// Result indicating success or failure of the operation
330
    fn install_console_ctrl_handler(&self) -> windows::core::Result<()>;
331
332
    /// Get standard output handle
333
    ///
334
    /// # Returns
335
    ///
336
    /// Handle to standard output or error
337
    fn get_stdout_handle(&self) -> windows::core::Result<HANDLE>;
338
339
    /// Get console screen buffer information
340
    ///
341
    /// # Arguments
342
    ///
343
    /// * `handle` - Handle to console screen buffer
344
    ///
345
    /// # Returns
346
    ///
347
    /// Console screen buffer information or error
348
    fn get_console_attached_process_count(&self) -> u32;
349
350
    /// Create a new process attached to its own console window.
351
    ///
352
    /// When `with_keyboard_focus` is false the new console window is
353
    /// shown without activation (`STARTF_USESHOWWINDOW` +
354
    /// `SW_SHOWNOACTIVATE`), so the caller retains keyboard focus.
355
    /// Used when the daemon spawns client consoles - otherwise the
356
    /// last-spawned client wins the foreground and Windows refuses to
357
    /// let the daemon steal it back.
358
    ///
359
    /// # Arguments
360
    ///
361
    /// * `application`         - Application name including file extension
362
    /// * `args`                - List of arguments to the application
363
    /// * `with_keyboard_focus` - Whether the new console window should take
364
    ///                           foreground focus when it appears.
365
    ///
366
    /// # Returns
367
    ///
368
    /// Process information if successful, None otherwise
369
1
    fn create_process_with_args(
370
1
        &self,
371
1
        application: &str,
372
1
        args: Vec<String>,
373
1
        with_keyboard_focus: bool,
374
1
    ) -> Option<windows::Win32::System::Threading::PROCESS_INFORMATION> {
375
1
        let command_line = build_command_line(application, &args);
376
1
        let mut startupinfo = build_startupinfo(with_keyboard_focus);
377
1
        let mut process_information = PROCESS_INFORMATION::default();
378
1
        let mut cmd_line = command_line;
379
1
        let command_line_ptr = windows::core::PWSTR(cmd_line.as_mut_ptr());
380
381
1
        match self.create_process_raw(
382
1
            application,
383
1
            command_line_ptr,
384
1
            &mut startupinfo,
385
1
            &mut process_information,
386
1
        ) {
387
1
            Ok(()) => return Some(process_information),
388
0
            Err(_) => return None,
389
        }
390
1
    }
391
392
    /// Create a new process from `OsStr`/`OsString` inputs without lossy
393
    /// UTF-8 conversion.
394
    ///
395
    /// Mirrors [`Self::create_process_with_args`] but preserves the
396
    /// platform-native UTF-16 representation of `application` and `args`.
397
    /// Use this from code that hands paths or user-supplied arguments
398
    /// straight to the spawner (e.g. the platform-trait
399
    /// `ProcessSpawner::spawn`) - non-UTF-8 sequences are passed through
400
    /// to `CreateProcessW` unmodified instead of being replaced with
401
    /// `U+FFFD`.
402
    ///
403
    /// # Arguments
404
    ///
405
    /// * `application`         - Application path or name.
406
    /// * `args`                - Arguments to the application.
407
    /// * `with_keyboard_focus` - Whether the new console window should
408
    ///                           take foreground focus when it appears.
409
    ///
410
    /// # Returns
411
    ///
412
    /// Process information on success, or the originating
413
    /// [`windows::core::Error`] from `CreateProcessW`.
414
0
    fn create_process_with_os_args(
415
0
        &self,
416
0
        application: &OsStr,
417
0
        args: &[OsString],
418
0
        with_keyboard_focus: bool,
419
0
    ) -> windows::core::Result<PROCESS_INFORMATION> {
420
0
        let app_wide = encode_wide_z(application);
421
0
        let mut cmd_line = build_command_line_wide(application, args);
422
0
        let mut startupinfo = build_startupinfo(with_keyboard_focus);
423
0
        let mut process_information = PROCESS_INFORMATION::default();
424
0
        let command_line_ptr = windows::core::PWSTR(cmd_line.as_mut_ptr());
425
426
0
        self.create_process_raw_wide(
427
0
            &app_wide,
428
0
            command_line_ptr,
429
0
            &mut startupinfo,
430
0
            &mut process_information,
431
0
        )?;
432
0
        return Ok(process_information);
433
0
    }
434
435
    /// Low-level `CreateProcessW` call accepting an already-wide,
436
    /// null-terminated application path.
437
    ///
438
    /// # Arguments
439
    ///
440
    /// * `application_wide` - UTF-16, null-terminated application path.
441
    /// * `command_line`     - Mutable UTF-16 command line as `PWSTR`.
442
    /// * `startup_info`     - Startup information structure.
443
    /// * `process_info`     - Output process information.
444
    ///
445
    /// # Returns
446
    ///
447
    /// Result indicating success or failure of the operation.
448
    fn create_process_raw_wide(
449
        &self,
450
        application_wide: &[u16],
451
        command_line: windows::core::PWSTR,
452
        startup_info: &mut windows::Win32::System::Threading::STARTUPINFOW,
453
        process_info: &mut windows::Win32::System::Threading::PROCESS_INFORMATION,
454
    ) -> windows::core::Result<()>;
455
456
    /// Low-level process creation API call
457
    ///
458
    /// # Arguments
459
    ///
460
    /// * `application` - Application name
461
    /// * `command_line` - Command line string as PWSTR
462
    /// * `startup_info` - Startup information structure
463
    /// * `process_info` - Process information structure to fill
464
    ///
465
    /// # Returns
466
    ///
467
    /// Result indicating success or failure of the operation
468
    fn create_process_raw(
469
        &self,
470
        application: &str,
471
        command_line: windows::core::PWSTR,
472
        startup_info: &mut windows::Win32::System::Threading::STARTUPINFOW,
473
        process_info: &mut windows::Win32::System::Threading::PROCESS_INFORMATION,
474
    ) -> windows::core::Result<()>;
475
476
    /// Get window handle for process ID
477
    ///
478
    /// # Arguments
479
    ///
480
    /// * `process_id` - Process ID to find window for
481
    ///
482
    /// # Returns
483
    ///
484
    /// Window handle for the process
485
    fn get_window_handle_for_process(&self, process_id: u32) -> HWND;
486
487
    /// Gets the console window handle.
488
    ///
489
    /// # Returns
490
    ///
491
    /// Handle to the console window
492
    fn get_console_window(&self) -> HWND;
493
494
    /// Gets the foreground window handle.
495
    ///
496
    /// # Returns
497
    ///
498
    /// Handle to the foreground window
499
    fn get_foreground_window(&self) -> HWND;
500
501
    /// Bring `hwnd` to the top of the z-order.
502
    ///
503
    /// When `with_keyboard_focus` is true the window is also activated and
504
    /// receives keyboard focus. When false the window is raised without
505
    /// activation, avoiding the taskbar flash that would happen if the
506
    /// window is not the current input target.
507
    ///
508
    /// # Arguments
509
    ///
510
    /// * `hwnd`                - Handle to the window to raise.
511
    /// * `with_keyboard_focus` - Whether to activate the window and give
512
    ///                           it keyboard focus.
513
    ///
514
    /// # Returns
515
    ///
516
    /// Result indicating success or failure of the operation
517
    fn bring_window_to_top(
518
        &self,
519
        hwnd: HWND,
520
        with_keyboard_focus: bool,
521
    ) -> windows::core::Result<()>;
522
523
    /// Gets console mode for the specified handle.
524
    ///
525
    /// # Arguments
526
    ///
527
    /// * `handle` - Handle to the console input buffer
528
    ///
529
    /// # Returns
530
    ///
531
    /// Console mode or error
532
    fn get_console_mode(&self, handle: HANDLE) -> windows::core::Result<CONSOLE_MODE>;
533
534
    /// Sets console mode for the specified handle.
535
    ///
536
    /// # Arguments
537
    ///
538
    /// * `handle` - Handle to the console input buffer
539
    /// * `mode` - Console mode to set
540
    ///
541
    /// # Returns
542
    ///
543
    /// Result indicating success or failure of the operation
544
    fn set_console_mode(&self, handle: HANDLE, mode: CONSOLE_MODE) -> windows::core::Result<()>;
545
546
    /// Gets the exit code of the specified process.
547
    ///
548
    /// # Arguments
549
    ///
550
    /// * `handle` - Handle to the process
551
    ///
552
    /// # Returns
553
    ///
554
    /// Exit code or error
555
    fn get_exit_code(&self, handle: HANDLE) -> windows::core::Result<u32>;
556
557
    /// Moves and resizes a window.
558
    ///
559
    /// # Arguments
560
    ///
561
    /// * `hwnd` - Handle to the window
562
    /// * `x` - New x position
563
    /// * `y` - New y position
564
    /// * `width` - New width
565
    /// * `height` - New height
566
    /// * `repaint` - Whether to repaint the window
567
    ///
568
    /// # Returns
569
    ///
570
    /// Result indicating success or failure of the operation
571
    fn move_window(
572
        &self,
573
        hwnd: HWND,
574
        x: i32,
575
        y: i32,
576
        width: i32,
577
        height: i32,
578
        repaint: bool,
579
    ) -> windows::core::Result<()>;
580
581
    /// Gets window placement information.
582
    ///
583
    /// # Arguments
584
    ///
585
    /// * `hwnd` - Handle to the window
586
    ///
587
    /// # Returns
588
    ///
589
    /// Window placement information or error
590
    fn get_window_placement(&self, hwnd: HWND) -> windows::core::Result<WINDOWPLACEMENT>;
591
592
    /// Shows a window in the specified state.
593
    ///
594
    /// # Arguments
595
    ///
596
    /// * `hwnd` - Handle to the window
597
    /// * `cmd_show` - Show command
598
    ///
599
    /// # Returns
600
    ///
601
    /// Result indicating success or failure of the operation
602
    fn show_window(&self, hwnd: HWND, cmd_show: SHOW_WINDOW_CMD) -> windows::core::Result<bool>;
603
604
    /// Checks if a window handle is valid.
605
    ///
606
    /// # Arguments
607
    ///
608
    /// * `hwnd` - Handle to the window to check
609
    ///
610
    /// # Returns
611
    ///
612
    /// True if the window is valid, false otherwise
613
    fn is_window(&self, hwnd: HWND) -> bool;
614
615
    /// Opens a process with the specified access rights.
616
    ///
617
    /// # Arguments
618
    ///
619
    /// * `access` - Access rights for the process handle
620
    /// * `inherit` - Whether the handle can be inherited
621
    /// * `process_id` - Process ID to open
622
    ///
623
    /// # Returns
624
    ///
625
    /// Process handle or error
626
    fn open_process(
627
        &self,
628
        access: u32,
629
        inherit: bool,
630
        process_id: u32,
631
    ) -> windows::core::Result<HANDLE>;
632
633
    /// Gets system metrics information.
634
    ///
635
    /// # Arguments
636
    ///
637
    /// * `index` - System metric index to retrieve
638
    ///
639
    /// # Returns
640
    ///
641
    /// The requested system metric value
642
    fn get_system_metrics(&self, index: SYSTEM_METRICS_INDEX) -> i32;
643
644
    /// Sets the process DPI awareness.
645
    ///
646
    /// # Arguments
647
    ///
648
    /// * `value` - DPI awareness value to set
649
    ///
650
    /// # Returns
651
    ///
652
    /// Result indicating success or failure of the operation
653
    fn set_process_dpi_awareness(
654
        &self,
655
        value: windows::Win32::UI::HiDpi::PROCESS_DPI_AWARENESS,
656
    ) -> windows::core::Result<()>;
657
}
658
659
#[cfg(any(test, feature = "mock"))]
660
impl Clone for MockWindowsApi {
661
0
    fn clone(&self) -> Self {
662
0
        return MockWindowsApi::new();
663
0
    }
664
}
665
666
/// Console control handler that swallows CTRL+C and CTRL+Break.
667
///
668
/// Returning `TRUE` marks the event as handled so it does not terminate this
669
/// process; other control events return `FALSE` to keep their default handling.
670
/// <https://learn.microsoft.com/en-us/windows/console/handlerroutine>
671
#[cfg_attr(coverage_nightly, coverage(off))]
672
unsafe extern "system" fn console_ctrl_handler(ctrl_type: u32) -> BOOL {
673
    return match ctrl_type {
674
        CTRL_C_EVENT | CTRL_BREAK_EVENT => TRUE,
675
        _ => FALSE,
676
    };
677
}
678
679
/// Default implementation of WindowsApi that calls actual Windows APIs.
680
///
681
/// This implementation provides direct access to Windows system APIs and should
682
/// be used in production code. For testing, use the MockWindowsApi instead.
683
#[derive(Clone)]
684
pub struct DefaultWindowsApi;
685
686
#[cfg_attr(coverage_nightly, coverage(off))]
687
impl WindowsApi for DefaultWindowsApi {
688
    fn set_console_title(&self, title: &str) -> windows::core::Result<()> {
689
        return unsafe { SetWindowTextW(GetConsoleWindow(), &HSTRING::from(title)) };
690
    }
691
692
    fn get_console_title(&self, buffer: &mut [u16]) -> i32 {
693
        return unsafe { GetWindowTextW(GetConsoleWindow(), buffer) };
694
    }
695
696
    fn get_os_version(&self) -> String {
697
        return os_info::get().version().to_string();
698
    }
699
700
    fn arrange_console(
701
        &self,
702
        x: i32,
703
        y: i32,
704
        width: i32,
705
        height: i32,
706
    ) -> windows::core::Result<()> {
707
        return unsafe { MoveWindow(GetConsoleWindow(), x, y, width, height, true) };
708
    }
709
710
    fn set_console_text_attribute(
711
        &self,
712
        attributes: CONSOLE_CHARACTER_ATTRIBUTES,
713
    ) -> windows::core::Result<()> {
714
        return unsafe { SetConsoleTextAttribute(self.get_stdout_handle()?, attributes) };
715
    }
716
717
    fn get_console_screen_buffer_info(&self) -> windows::core::Result<CONSOLE_SCREEN_BUFFER_INFO> {
718
        let mut buffer_info = CONSOLE_SCREEN_BUFFER_INFO::default();
719
        unsafe { GetConsoleScreenBufferInfo(self.get_stdout_handle()?, &mut buffer_info)? };
720
        return Ok(buffer_info);
721
    }
722
723
    fn fill_console_output_attribute(
724
        &self,
725
        attribute: u16,
726
        length: u32,
727
        coord: COORD,
728
    ) -> windows::core::Result<u32> {
729
        let mut number_written = 0u32;
730
        unsafe {
731
            FillConsoleOutputAttribute(
732
                self.get_stdout_handle()?,
733
                attribute,
734
                length,
735
                coord,
736
                &mut number_written,
737
            )?
738
        };
739
        return Ok(number_written);
740
    }
741
742
    fn read_console_output_attribute(
743
        &self,
744
        length: u32,
745
        coord: COORD,
746
    ) -> windows::core::Result<Vec<u16>> {
747
        let mut attributes = vec![0u16; length as usize];
748
        let mut number_read = 0u32;
749
        unsafe {
750
            ReadConsoleOutputAttribute(
751
                self.get_stdout_handle()?,
752
                &mut attributes,
753
                coord,
754
                &mut number_read,
755
            )?
756
        };
757
        attributes.truncate(number_read as usize);
758
        return Ok(attributes);
759
    }
760
761
    fn write_console_output_attribute(
762
        &self,
763
        attributes: &[u16],
764
        coord: COORD,
765
    ) -> windows::core::Result<u32> {
766
        let mut number_written = 0u32;
767
        unsafe {
768
            WriteConsoleOutputAttribute(
769
                self.get_stdout_handle()?,
770
                attributes,
771
                coord,
772
                &mut number_written,
773
            )?
774
        };
775
        return Ok(number_written);
776
    }
777
778
    fn get_console_screen_buffer_info_ex(
779
        &self,
780
    ) -> windows::core::Result<CONSOLE_SCREEN_BUFFER_INFOEX> {
781
        let mut info = CONSOLE_SCREEN_BUFFER_INFOEX {
782
            cbSize: mem::size_of::<CONSOLE_SCREEN_BUFFER_INFOEX>() as u32,
783
            ..Default::default()
784
        };
785
        unsafe { GetConsoleScreenBufferInfoEx(self.get_stdout_handle()?, &mut info)? };
786
        return Ok(info);
787
    }
788
789
    fn set_console_screen_buffer_info_ex(
790
        &self,
791
        info: &CONSOLE_SCREEN_BUFFER_INFOEX,
792
    ) -> windows::core::Result<()> {
793
        return unsafe { SetConsoleScreenBufferInfoEx(self.get_stdout_handle()?, info) };
794
    }
795
796
    fn scroll_console_screen_buffer(
797
        &self,
798
        scroll_rect: SMALL_RECT,
799
        scroll_target: COORD,
800
        fill_char: CHAR_INFO,
801
    ) -> windows::core::Result<()> {
802
        return unsafe {
803
            ScrollConsoleScreenBufferW(
804
                self.get_stdout_handle()?,
805
                &scroll_rect,
806
                None,
807
                scroll_target,
808
                &fill_char,
809
            )
810
        };
811
    }
812
813
    fn set_console_cursor_position(&self, position: COORD) -> windows::core::Result<()> {
814
        return unsafe { SetConsoleCursorPosition(self.get_stdout_handle()?, position) };
815
    }
816
817
    fn get_std_handle(&self, handle_type: STD_HANDLE) -> windows::core::Result<HANDLE> {
818
        return unsafe { GetStdHandle(handle_type) };
819
    }
820
821
    fn read_console_input(&self, buffer: &mut [INPUT_RECORD]) -> windows::core::Result<u32> {
822
        let mut number_read = 0u32;
823
        unsafe {
824
            ReadConsoleInputW(
825
                self.get_std_handle(STD_INPUT_HANDLE)?,
826
                buffer,
827
                &mut number_read,
828
            )?
829
        };
830
        return Ok(number_read);
831
    }
832
833
    fn set_console_border_color(&self, color: &COLORREF) -> windows::core::Result<()> {
834
        return unsafe {
835
            DwmSetWindowAttribute(
836
                GetConsoleWindow(),
837
                DWMWA_BORDER_COLOR,
838
                color as *const COLORREF as *const _,
839
                mem::size_of::<COLORREF>() as u32,
840
            )
841
        };
842
    }
843
844
    fn invalidate_console_window(&self) -> windows::core::Result<()> {
845
        let succeeded = unsafe { InvalidateRect(Some(GetConsoleWindow()), None, false) };
846
        if succeeded.as_bool() {
847
            return Ok(());
848
        }
849
        return Err(windows::core::Error::from_thread());
850
    }
851
852
    fn write_console_input(
853
        &self,
854
        buffer: &[INPUT_RECORD],
855
        number_written: &mut u32,
856
    ) -> windows::core::Result<()> {
857
        unsafe {
858
            windows::Win32::System::Console::WriteConsoleInputW(
859
                GetStdHandle(STD_INPUT_HANDLE)?,
860
                buffer,
861
                number_written,
862
            )?
863
        };
864
        return Ok(());
865
    }
866
867
    fn get_last_error(&self) -> u32 {
868
        return unsafe { windows::Win32::Foundation::GetLastError().0 };
869
    }
870
871
    fn interrupt_console_process_group(&self) -> windows::core::Result<()> {
872
        return unsafe {
873
            windows::Win32::System::Console::GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0)
874
        };
875
    }
876
877
    fn generate_console_ctrl_event(
878
        &self,
879
        ctrl_event: u32,
880
        process_group_id: u32,
881
    ) -> windows::core::Result<()> {
882
        return unsafe {
883
            windows::Win32::System::Console::GenerateConsoleCtrlEvent(ctrl_event, process_group_id)
884
        };
885
    }
886
887
    fn install_console_ctrl_handler(&self) -> windows::core::Result<()> {
888
        return unsafe { SetConsoleCtrlHandler(Some(console_ctrl_handler), true) };
889
    }
890
891
    fn get_stdout_handle(&self) -> windows::core::Result<HANDLE> {
892
        return self.get_std_handle(STD_OUTPUT_HANDLE);
893
    }
894
895
    fn get_console_attached_process_count(&self) -> u32 {
896
        let mut value: [u32; 1] = [0];
897
        unsafe { return GetConsoleProcessList(&mut value) };
898
    }
899
900
    fn get_window_handle_for_process(&self, process_id: u32) -> HWND {
901
        /// Data structure for window search callback
902
        struct WindowSearchData {
903
            /// The process ID we're searching for
904
            target_process_id: u32,
905
            /// Mutable reference to store the found window handle
906
            found_handle: *mut Option<HWND>,
907
        }
908
909
        /// Callback function for finding windows by process ID with proper handle capture
910
        unsafe extern "system" fn find_window_callback_with_capture(
911
            hwnd: HWND,
912
            lparam: LPARAM,
913
        ) -> BOOL {
914
            let search_data = &mut *(lparam.0 as *mut WindowSearchData);
915
            let mut window_process_id: u32 = 0;
916
            GetWindowThreadProcessId(hwnd, Some(&mut window_process_id));
917
918
            if search_data.target_process_id == window_process_id {
919
                // Store the found window handle
920
                *search_data.found_handle = Some(hwnd);
921
                return FALSE; // Stop enumeration
922
            }
923
            return TRUE; // Continue enumeration
924
        }
925
926
        let mut found_handle = None;
927
        let mut search_data = WindowSearchData {
928
            target_process_id: process_id,
929
            found_handle: &mut found_handle,
930
        };
931
932
        loop {
933
            let _ = unsafe {
934
                EnumWindows(
935
                    Some(find_window_callback_with_capture),
936
                    LPARAM(&mut search_data as *mut WindowSearchData as isize),
937
                )
938
            };
939
            if let Some(handle) = found_handle {
940
                return handle;
941
            }
942
        }
943
    }
944
945
    fn create_process_raw(
946
        &self,
947
        application: &str,
948
        command_line: windows::core::PWSTR,
949
        startup_info: &mut windows::Win32::System::Threading::STARTUPINFOW,
950
        process_info: &mut windows::Win32::System::Threading::PROCESS_INFORMATION,
951
    ) -> windows::core::Result<()> {
952
        return unsafe {
953
            CreateProcessW(
954
                &HSTRING::from(application),
955
                Some(command_line),
956
                Some(ptr::null_mut()),
957
                Some(ptr::null_mut()),
958
                false,
959
                CREATE_NEW_CONSOLE,
960
                Some(ptr::null_mut()),
961
                PCWSTR::null(),
962
                ptr::addr_of_mut!(*startup_info),
963
                ptr::addr_of_mut!(*process_info),
964
            )
965
        };
966
    }
967
968
    fn create_process_raw_wide(
969
        &self,
970
        application_wide: &[u16],
971
        command_line: windows::core::PWSTR,
972
        startup_info: &mut windows::Win32::System::Threading::STARTUPINFOW,
973
        process_info: &mut windows::Win32::System::Threading::PROCESS_INFORMATION,
974
    ) -> windows::core::Result<()> {
975
        let app_pcwstr = if application_wide.is_empty() {
976
            PCWSTR::null()
977
        } else {
978
            PCWSTR(application_wide.as_ptr())
979
        };
980
        return unsafe {
981
            CreateProcessW(
982
                app_pcwstr,
983
                Some(command_line),
984
                Some(ptr::null_mut()),
985
                Some(ptr::null_mut()),
986
                false,
987
                CREATE_NEW_CONSOLE,
988
                Some(ptr::null_mut()),
989
                PCWSTR::null(),
990
                ptr::addr_of_mut!(*startup_info),
991
                ptr::addr_of_mut!(*process_info),
992
            )
993
        };
994
    }
995
996
    fn get_console_window(&self) -> HWND {
997
        return unsafe { GetConsoleWindow() };
998
    }
999
1000
    fn get_foreground_window(&self) -> HWND {
1001
        return unsafe { GetForegroundWindow() };
1002
    }
1003
1004
    fn bring_window_to_top(
1005
        &self,
1006
        hwnd: HWND,
1007
        with_keyboard_focus: bool,
1008
    ) -> windows::core::Result<()> {
1009
        if with_keyboard_focus {
1010
            return unsafe { BringWindowToTop(hwnd) };
1011
        }
1012
        // Raise without activation via the HWND_TOPMOST -> HWND_NOTOPMOST
1013
        // trick. Synchronous SetWindowPos (no SWP_ASYNCWINDOWPOS) so
1014
        // HWND_TOPMOST is applied before we strip it again - otherwise
1015
        // rapid invocations from the z-order loop can leave the
1016
        // WS_EX_TOPMOST flag set, floating client windows above other
1017
        // applications. See https://stackoverflow.com/questions/5257977.
1018
        unsafe {
1019
            SetWindowPos(
1020
                hwnd,
1021
                Some(HWND_TOPMOST),
1022
                0,
1023
                0,
1024
                0,
1025
                0,
1026
                SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE,
1027
            )?;
1028
            SetWindowPos(
1029
                hwnd,
1030
                Some(HWND_NOTOPMOST),
1031
                0,
1032
                0,
1033
                0,
1034
                0,
1035
                SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE,
1036
            )?;
1037
        }
1038
        return Ok(());
1039
    }
1040
1041
    fn get_console_mode(&self, handle: HANDLE) -> windows::core::Result<CONSOLE_MODE> {
1042
        let mut mode = CONSOLE_MODE(0u32);
1043
        unsafe { GetConsoleMode(handle, &mut mode)? };
1044
        return Ok(mode);
1045
    }
1046
1047
    fn set_console_mode(&self, handle: HANDLE, mode: CONSOLE_MODE) -> windows::core::Result<()> {
1048
        return unsafe { SetConsoleMode(handle, mode) };
1049
    }
1050
1051
    fn get_exit_code(&self, handle: HANDLE) -> windows::core::Result<u32> {
1052
        let mut exit_code: u32 = 0;
1053
        unsafe { GetExitCodeProcess(handle, &mut exit_code)? };
1054
        return Ok(exit_code);
1055
    }
1056
1057
    fn move_window(
1058
        &self,
1059
        hwnd: HWND,
1060
        x: i32,
1061
        y: i32,
1062
        width: i32,
1063
        height: i32,
1064
        repaint: bool,
1065
    ) -> windows::core::Result<()> {
1066
        return unsafe { MoveWindow(hwnd, x, y, width, height, repaint) };
1067
    }
1068
1069
    fn get_window_placement(&self, hwnd: HWND) -> windows::core::Result<WINDOWPLACEMENT> {
1070
        let mut placement: WINDOWPLACEMENT = WINDOWPLACEMENT {
1071
            length: mem::size_of::<WINDOWPLACEMENT>() as u32,
1072
            ..Default::default()
1073
        };
1074
        unsafe { GetWindowPlacement(hwnd, &mut placement)? };
1075
        return Ok(placement);
1076
    }
1077
1078
    fn show_window(&self, hwnd: HWND, cmd_show: SHOW_WINDOW_CMD) -> windows::core::Result<bool> {
1079
        let result = unsafe { ShowWindow(hwnd, cmd_show) };
1080
        return Ok(result.as_bool());
1081
    }
1082
1083
    fn is_window(&self, hwnd: HWND) -> bool {
1084
        return unsafe { windows::Win32::UI::WindowsAndMessaging::IsWindow(Some(hwnd)).as_bool() };
1085
    }
1086
1087
    fn open_process(
1088
        &self,
1089
        access: u32,
1090
        inherit: bool,
1091
        process_id: u32,
1092
    ) -> windows::core::Result<HANDLE> {
1093
        return unsafe { OpenProcess(PROCESS_ACCESS_RIGHTS(access), inherit, process_id) };
1094
    }
1095
1096
    fn get_system_metrics(&self, index: SYSTEM_METRICS_INDEX) -> i32 {
1097
        return unsafe { windows::Win32::UI::WindowsAndMessaging::GetSystemMetrics(index) };
1098
    }
1099
1100
    fn set_process_dpi_awareness(
1101
        &self,
1102
        value: windows::Win32::UI::HiDpi::PROCESS_DPI_AWARENESS,
1103
    ) -> windows::core::Result<()> {
1104
        return unsafe { windows::Win32::UI::HiDpi::SetProcessDpiAwareness(value) };
1105
    }
1106
}
1107
1108
/// u16 representation of a [KEY_EVENT][1].
1109
///
1110
/// For some reason the public [KEY_EVENT][1] constant is a u32
1111
/// while the [INPUT_RECORD][2].`EventType` is u16...
1112
///
1113
/// [1]: https://microsoft.github.io/windows-docs-rs/doc/windows/Win32/System/Console/constant.KEY_EVENT.html
1114
/// [2]: https://microsoft.github.io/windows-docs-rs/doc/windows/Win32/System/Console/struct.INPUT_RECORD.html
1115
pub const KEY_EVENT: u16 = KEY_EVENT_U32 as u16;
1116
1117
/// Build a `STARTUPINFOW` for [`WindowsApi::create_process_with_args`].
1118
///
1119
/// When `with_keyboard_focus` is false, `STARTF_USESHOWWINDOW` and
1120
/// `SW_SHOWNOACTIVATE` are populated so the new console appears without
1121
/// stealing foreground focus. Otherwise the struct is left at its default
1122
/// (the new process picks its own show-window behaviour).
1123
///
1124
/// # Arguments
1125
///
1126
/// * `with_keyboard_focus` - Whether the spawned process is allowed to take
1127
///                           foreground focus when its console appears.
1128
///
1129
/// # Returns
1130
///
1131
/// A `STARTUPINFOW` with `cb` set and, when applicable, the no-activate
1132
/// show-window flags applied.
1133
3
pub(crate) fn build_startupinfo(with_keyboard_focus: bool) -> STARTUPINFOW {
1134
3
    let mut startupinfo = STARTUPINFOW {
1135
3
        cb: mem::size_of::<STARTUPINFOW>() as u32,
1136
3
        ..Default::default()
1137
3
    };
1138
3
    if !with_keyboard_focus {
1139
1
        startupinfo.dwFlags = STARTF_USESHOWWINDOW;
1140
1
        startupinfo.wShowWindow = SW_SHOWNOACTIVATE.0 as u16;
1141
2
    }
1142
3
    return startupinfo;
1143
3
}
1144
1145
/// Build command line string for Windows process creation
1146
///
1147
/// # Arguments
1148
///
1149
/// * `application` - Application name including file extension
1150
/// * `args` - List of arguments to the application
1151
///
1152
/// # Returns
1153
///
1154
/// UTF-16 encoded command line with proper quoting
1155
///
1156
/// # Examples
1157
///
1158
/// ```
1159
/// use cssh_rs_platform_windows::build_command_line;
1160
///
1161
/// let cmd_line = build_command_line("cmd.exe", &["arg1".to_string(), "arg2".to_string()]);
1162
/// // Returns UTF-16 encoded: "cmd.exe" "arg1" "arg2"\0
1163
/// ```
1164
5
pub fn build_command_line(application: &str, args: &[String]) -> Vec<u16> {
1165
5
    let mut cmd: Vec<u16> = Vec::new();
1166
5
    cmd.push(b'"' as u16);
1167
5
    cmd.extend(OsString::from(application).encode_wide());
1168
5
    cmd.push(b'"' as u16);
1169
1170
7
    for arg in 
args5
{
1171
7
        cmd.push(' ' as u16);
1172
7
        cmd.push(b'"' as u16);
1173
7
        cmd.extend(OsString::from(arg).encode_wide());
1174
7
        cmd.push(b'"' as u16);
1175
7
    }
1176
5
    cmd.push(0); // add null terminator
1177
1178
5
    return cmd;
1179
5
}
1180
1181
/// Build a UTF-16, null-terminated command line directly from `OsStr`
1182
/// inputs.
1183
///
1184
/// Mirrors [`build_command_line`] but skips the `&str`/`String` round-trip
1185
/// so non-UTF-8 byte sequences (typical for paths and user-supplied
1186
/// arguments on Windows) survive intact.
1187
///
1188
/// # Arguments
1189
///
1190
/// * `application` - Application path or name.
1191
/// * `args`        - Arguments to the application.
1192
///
1193
/// # Returns
1194
///
1195
/// UTF-16 encoded command line with proper quoting.
1196
3
pub fn build_command_line_wide(application: &OsStr, args: &[OsString]) -> Vec<u16> {
1197
3
    let mut cmd: Vec<u16> = Vec::new();
1198
3
    cmd.push(b'"' as u16);
1199
3
    cmd.extend(application.encode_wide());
1200
3
    cmd.push(b'"' as u16);
1201
1202
3
    for arg in args {
1203
3
        cmd.push(' ' as u16);
1204
3
        cmd.push(b'"' as u16);
1205
3
        cmd.extend(arg.encode_wide());
1206
3
        cmd.push(b'"' as u16);
1207
3
    }
1208
3
    cmd.push(0);
1209
1210
3
    return cmd;
1211
3
}
1212
1213
/// UTF-16 encode `s` with a trailing null terminator.
1214
///
1215
/// # Arguments
1216
///
1217
/// * `s` - String to encode.
1218
///
1219
/// # Returns
1220
///
1221
/// UTF-16 encoded buffer suitable for passing to wide-string Win32 APIs
1222
/// such as `CreateProcessW`'s `lpApplicationName`.
1223
2
pub(crate) fn encode_wide_z(s: &OsStr) -> Vec<u16> {
1224
2
    let mut out: Vec<u16> = s.encode_wide().collect();
1225
2
    out.push(0);
1226
2
    return out;
1227
2
}
1228
1229
/// Sets the back- and foreground color of the current console window using the provided API.
1230
///
1231
/// # Arguments
1232
///
1233
/// * `api` - The Windows API implementation to use.
1234
/// * `color` - The color value describing the back- and foreground color.
1235
///
1236
/// # Examples
1237
///
1238
/// ```no_run
1239
/// use cssh_rs_platform_windows::{set_console_color, DefaultWindowsApi};
1240
/// use windows::Win32::System::Console::CONSOLE_CHARACTER_ATTRIBUTES;
1241
///
1242
/// let api = DefaultWindowsApi;
1243
/// set_console_color(&api, CONSOLE_CHARACTER_ATTRIBUTES(0x0F));
1244
/// ```
1245
3
pub fn set_console_color(api: &dyn WindowsApi, color: CONSOLE_CHARACTER_ATTRIBUTES) {
1246
3
    api.set_console_text_attribute(color).unwrap();
1247
3
    let buffer_info = api.get_console_screen_buffer_info().unwrap();
1248
    // FillConsoleOutputAttribute continues into successive rows when the
1249
    // length extends past the end of the row, so a single call from (0,0)
1250
    // recolors the entire buffer in one LPC roundtrip.
1251
3
    let width: u32 = buffer_info.dwSize.X.try_into().unwrap();
1252
3
    let height: u32 = buffer_info.dwSize.Y.try_into().unwrap();
1253
3
    api.fill_console_output_attribute(color.0, width * height, COORD { X: 0, Y: 0 })
1254
3
        .unwrap();
1255
    // The console client area can contain a sub-cell-sized pixel sliver at
1256
    // the right and/or bottom edge when the OS window pixel dimensions do
1257
    // not divide evenly into the cell grid (cssh-rs clients are sized in
1258
    // pixels via MoveWindow). Those slivers are not backed by any buffer
1259
    // cell, so the fill above cannot reach them, and conhost does not
1260
    // repaint them on an attribute-only update - they keep the old color
1261
    // until something triggers a WM_PAINT (user double-clicking is one
1262
    // such trigger).
1263
3
    if let Err(
err2
) = api.invalidate_console_window() {
1264
2
        warn!("Failed to invalidate console window after recolor: {}", err);
1265
1
    }
1266
3
}
1267
1268
/// The console's captured 16-entry palette plus its default text attribute
1269
/// (kept so the tint can locate the default text/background entries in
1270
/// `color_table`).
1271
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1272
pub struct ConsolePaletteSnapshot {
1273
    /// The 16-entry RGB color table.
1274
    pub color_table: [COLORREF; 16],
1275
    /// The default screen text attribute.
1276
    pub default_attributes: CONSOLE_CHARACTER_ATTRIBUTES,
1277
}
1278
1279
/// Snapshots the console's 16-entry RGB palette and default text attribute for a
1280
/// later restore and for locating the default foreground/background entries the
1281
/// tint recolors.
1282
///
1283
/// # Arguments
1284
///
1285
/// * `api` - The Windows API implementation to use.
1286
///
1287
/// # Returns
1288
///
1289
/// `Some(snapshot)` on success, or `None` if the buffer info could not be read
1290
/// (state visuals degrade to a no-op rather than aborting the session).
1291
4
pub fn snapshot_console_palette(api: &dyn WindowsApi) -> Option<ConsolePaletteSnapshot> {
1292
4
    match api.get_console_screen_buffer_info_ex() {
1293
3
        Ok(info) => {
1294
3
            return Some(ConsolePaletteSnapshot {
1295
3
                color_table: info.ColorTable,
1296
3
                default_attributes: info.wAttributes,
1297
3
            })
1298
        }
1299
1
        Err(err) => {
1300
1
            warn!(
1301
                "Failed to read console palette; state visuals will be skipped: {}",
1302
                err
1303
            );
1304
1
            return None;
1305
        }
1306
    }
1307
4
}
1308
1309
/// Derive the tinted palette for a state color: the captured palette with the
1310
/// console's default-foreground and default-background entries remapped to the
1311
/// colors the legacy `tint` attribute's foreground and background nibbles select.
1312
/// Recoloring palette entries (never the per-cell attributes) leaves VT/24-bit
1313
/// cells - which store their color outside the palette - untouched, so the full
1314
/// configured color applies without hiding the child's own colored output.
1315
///
1316
/// # Arguments
1317
///
1318
/// * `snapshot` - The pristine palette captured by [`snapshot_console_palette`].
1319
/// * `tint`     - Legacy attribute whose foreground and background nibbles select
1320
///                the tint's text and window colors.
1321
///
1322
/// # Returns
1323
///
1324
/// The palette to install for the tinted look.
1325
8
pub fn tinted_palette(
1326
8
    snapshot: &ConsolePaletteSnapshot,
1327
8
    tint: CONSOLE_CHARACTER_ATTRIBUTES,
1328
8
) -> [COLORREF; 16] {
1329
8
    let base = &snapshot.color_table;
1330
8
    let default = snapshot.default_attributes.0;
1331
8
    let default_foreground_index = (default & 0x0F) as usize;
1332
8
    let default_background_index = ((default >> 4) & 0x0F) as usize;
1333
8
    let requested_foreground = base[(tint.0 & 0x0F) as usize];
1334
8
    let requested_background = base[((tint.0 >> 4) & 0x0F) as usize];
1335
8
    let mut palette = *base;
1336
8
    palette[default_foreground_index] = requested_foreground;
1337
8
    palette[default_background_index] = requested_background;
1338
8
    return palette;
1339
8
}
1340
1341
/// Installs `palette` as the console's 16-entry color table, leaving the rest of
1342
/// the buffer info as it currently is, and forces a repaint.
1343
///
1344
/// # Arguments
1345
///
1346
/// * `api`     - The Windows API implementation to use.
1347
/// * `palette` - The 16 RGB entries to install.
1348
///
1349
/// # Returns
1350
///
1351
/// `true` if the palette was written, `false` if reading or writing the buffer
1352
/// info failed so the caller can keep its snapshot and retry the paint.
1353
13
pub fn set_console_palette(api: &dyn WindowsApi, palette: &[COLORREF; 16]) -> bool {
1354
13
    let 
mut info12
= match api.get_console_screen_buffer_info_ex() {
1355
12
        Ok(info) => info,
1356
1
        Err(err) => {
1357
1
            warn!("Failed to read console palette before recolor: {}", err);
1358
1
            return false;
1359
        }
1360
    };
1361
12
    info.ColorTable = *palette;
1362
    // SetConsoleScreenBufferInfoEx shrinks the window by one cell per call; widen srWindow to keep it stable.
1363
    // <https://stackoverflow.com/questions/35901572>
1364
12
    info.srWindow.Right += 1;
1365
12
    info.srWindow.Bottom += 1;
1366
12
    if let Err(
err1
) = api.set_console_screen_buffer_info_ex(&info) {
1367
1
        warn!("Failed to apply console palette: {}", err);
1368
1
        return false;
1369
11
    }
1370
11
    if let Err(
err0
) = api.invalidate_console_window() {
1371
0
        warn!(
1372
            "Failed to invalidate console window after palette change: {}",
1373
            err
1374
        );
1375
11
    }
1376
11
    return true;
1377
13
}
1378
1379
/// Empties the console screen output buffer of the current console window using the provided API.
1380
///
1381
/// # Arguments
1382
///
1383
/// * `api` - The Windows API implementation to use.
1384
///
1385
/// # Examples
1386
///
1387
/// ```no_run
1388
/// use cssh_rs_platform_windows::{clear_screen, DefaultWindowsApi};
1389
///
1390
/// let api = DefaultWindowsApi;
1391
/// clear_screen(&api);
1392
/// ```
1393
7
pub fn clear_screen(api: &dyn WindowsApi) {
1394
7
    let buffer_info = api.get_console_screen_buffer_info().unwrap();
1395
7
    let scroll_rect = SMALL_RECT {
1396
7
        Left: 0,
1397
7
        Top: 0,
1398
7
        Right: buffer_info.dwSize.X,
1399
7
        Bottom: buffer_info.dwSize.Y,
1400
7
    };
1401
7
    let scroll_target = COORD {
1402
7
        X: buffer_info.dwSize.X,
1403
7
        Y: 0 - buffer_info.dwSize.Y,
1404
7
    };
1405
7
    let mut char_info = CHAR_INFO::default();
1406
7
    char_info.Char.UnicodeChar = ' ' as u16;
1407
7
    char_info.Attributes = buffer_info.wAttributes.0;
1408
1409
7
    api.scroll_console_screen_buffer(scroll_rect, scroll_target, char_info)
1410
7
        .unwrap();
1411
1412
7
    let cursor_position = COORD { X: 0, Y: 0 };
1413
7
    api.set_console_cursor_position(cursor_position).unwrap();
1414
7
}
1415
1416
/// Sets the border color of the current console window using the provided APIs.
1417
///
1418
/// Windows10 does not support this.
1419
///
1420
/// # Arguments
1421
///
1422
/// * `api` - The Windows API implementation;
1423
/// * `color` - RGB [COLORREF][1] to set as border color.
1424
///
1425
/// # Examples
1426
///
1427
/// ```no_run
1428
/// use cssh_rs_platform_windows::{set_console_border_color, DefaultWindowsApi};
1429
/// use windows::Win32::Foundation::COLORREF;
1430
///
1431
/// set_console_border_color(&DefaultWindowsApi, COLORREF(0x001A2B3C));
1432
/// ```
1433
///
1434
/// [1]: https://learn.microsoft.com/en-us/windows/win32/gdi/colorref
1435
3
pub fn set_console_border_color(api: &dyn WindowsApi, color: COLORREF) {
1436
3
    if !is_windows_10(api) {
1437
2
        api.set_console_border_color(&color).unwrap();
1438
2
    
}1
1439
3
}
1440
1441
/// Converts a UTF-16 buffer to a Rust String, filtering out null characters.
1442
///
1443
/// # Arguments
1444
///
1445
/// * `buffer` - The UTF-16 buffer to convert.
1446
///
1447
/// # Returns
1448
///
1449
/// The converted string.
1450
///
1451
/// # Examples
1452
///
1453
/// ```
1454
/// use cssh_rs_platform_windows::utf16_buffer_to_string;
1455
///
1456
/// let utf16_data = vec![72, 101, 108, 108, 111, 0]; // "Hello" + null terminator
1457
/// let result = utf16_buffer_to_string(&utf16_data);
1458
/// assert_eq!(result, "Hello");
1459
/// ```
1460
6
pub fn utf16_buffer_to_string(buffer: &[u16]) -> String {
1461
6
    let vec: Vec<u16> = buffer
1462
6
        .iter()
1463
6
        .copied()
1464
55
        .
filter6
(|val| return *val != 0u16)
1465
6
        .collect();
1466
6
    return String::from_utf16(&vec).unwrap_or_else(|err| 
{0
1467
0
        error!("{}", err);
1468
0
        panic!("Failed to convert UTF-16 buffer to string, invalid utf16")
1469
    });
1470
6
}
1471
1472
/// Returns the title of the current console window using the provided API.
1473
///
1474
/// # Arguments
1475
///
1476
/// * `api` - The Windows API implementation to use.
1477
///
1478
/// # Returns
1479
///
1480
/// The title of the current console window.
1481
///
1482
/// # Examples
1483
///
1484
/// ```no_run
1485
/// use cssh_rs_platform_windows::{get_console_title, DefaultWindowsApi};
1486
///
1487
/// let title = get_console_title(&DefaultWindowsApi);
1488
/// println!("Console title: {}", title);
1489
/// ```
1490
0
pub fn get_console_title(api: &dyn WindowsApi) -> String {
1491
0
    let mut title: [u16; MAX_WINDOW_TITLE_LENGTH] = [0; MAX_WINDOW_TITLE_LENGTH];
1492
0
    api.get_console_title(&mut title);
1493
0
    return utf16_buffer_to_string(&title);
1494
0
}
1495
1496
/// Returns a [HANDLE] to the requested [STD_HANDLE] of the current process.
1497
///
1498
/// # Arguments
1499
///
1500
/// * `nstdhandle` - The standard handle to retrieve.
1501
///                  Either [STD_INPUT_HANDLE] or [STD_OUTPUT_HANDLE].
1502
///
1503
/// # Returns
1504
///
1505
/// The [HANDLE] to the requested [STD_HANDLE].
1506
#[cfg_attr(coverage_nightly, coverage(off))]
1507
fn get_std_handle(nstdhandle: STD_HANDLE) -> HANDLE {
1508
    return unsafe {
1509
        GetStdHandle(nstdhandle)
1510
            .unwrap_or_else(|_| panic!("Failed to retrieve standard handle: {nstdhandle:?}"))
1511
    };
1512
}
1513
1514
/// Returns a [HANDLE] to the [STD_INPUT_HANDLE] of the current process.
1515
///
1516
/// # Returns
1517
///
1518
/// Handle to the standard input of the current process.
1519
///
1520
/// # Examples
1521
///
1522
/// ```no_run
1523
/// use cssh_rs_platform_windows::get_console_input_buffer;
1524
///
1525
/// let input_handle = get_console_input_buffer();
1526
/// ```
1527
#[cfg_attr(coverage_nightly, coverage(off))]
1528
pub fn get_console_input_buffer() -> HANDLE {
1529
    return get_std_handle(STD_INPUT_HANDLE);
1530
}
1531
1532
/// Returns a [HANDLE] to the [STD_OUTPUT_HANDLE] of the current process.
1533
///
1534
/// # Returns
1535
///
1536
/// Handle to the standard output of the current process.
1537
///
1538
/// # Examples
1539
///
1540
/// ```no_run
1541
/// use cssh_rs_platform_windows::get_console_output_buffer;
1542
///
1543
/// let output_handle = get_console_output_buffer();
1544
/// ```
1545
#[cfg_attr(coverage_nightly, coverage(off))]
1546
pub fn get_console_output_buffer() -> HANDLE {
1547
    return get_std_handle(STD_OUTPUT_HANDLE);
1548
}
1549
1550
/// Returns a single [INPUT_RECORD] read from the current process stdinput using the provided API.
1551
///
1552
/// Blocks until 1 record was read.
1553
///
1554
/// # Arguments
1555
///
1556
/// * `api` - The Windows API implementation to use.
1557
///
1558
/// # Returns
1559
///
1560
/// A single INPUT_RECORD that was read.
1561
///
1562
/// # Examples
1563
///
1564
/// ```no_run
1565
/// use cssh_rs_platform_windows::{read_console_input, DefaultWindowsApi};
1566
///
1567
/// let api = DefaultWindowsApi;
1568
/// let input_record = read_console_input(&api);
1569
/// ```
1570
5
pub fn read_console_input(api: &dyn WindowsApi) -> INPUT_RECORD {
1571
    const NB_EVENTS: usize = 1;
1572
5
    let mut input_buffer: [INPUT_RECORD; NB_EVENTS] = [INPUT_RECORD::default(); NB_EVENTS];
1573
    loop {
1574
6
        let number_of_events_read = api
1575
6
            .read_console_input(&mut input_buffer)
1576
6
            .expect("Failed to read console input");
1577
6
        if number_of_events_read == NB_EVENTS as u32 {
1578
5
            break;
1579
1
        }
1580
    }
1581
5
    return input_buffer[0];
1582
5
}
1583
1584
/// Returns a single [INPUT_RECORD_0] where `EventType` == [`KEY_EVENT`] using the provided API.
1585
///
1586
/// Blocks until 1 key event record was read.
1587
///
1588
/// # Arguments
1589
///
1590
/// * `api` - The Windows API implementation to use.
1591
///
1592
/// # Returns
1593
///
1594
/// A single INPUT_RECORD_0 with EventType == KEY_EVENT.
1595
///
1596
/// # Examples
1597
///
1598
/// ```no_run
1599
/// use cssh_rs_platform_windows::{read_keyboard_input, DefaultWindowsApi};
1600
///
1601
/// let api = DefaultWindowsApi;
1602
/// let key_event = read_keyboard_input(&api);
1603
/// ```
1604
1
pub fn read_keyboard_input(api: &dyn WindowsApi) -> INPUT_RECORD_0 {
1605
    loop {
1606
2
        let input_record = read_console_input(api);
1607
2
        match input_record.EventType {
1608
            KEY_EVENT => {
1609
1
                return input_record.Event;
1610
            }
1611
            _ => {
1612
1
                continue;
1613
            }
1614
        }
1615
    }
1616
1
}
1617
1618
/// Changes size and position of the current console window using the provided API.
1619
///
1620
/// # Arguments
1621
///
1622
/// * `api` - The Windows API implementation to use.
1623
/// * `x`       - The x coordinate to move the window to.
1624
///               From the top left corner of the screen.
1625
/// * `y`       - The y coordinate to move the window to.
1626
///               From the top left corner of the screen.
1627
/// * `width`   - The width in pixels to resize the window to.
1628
///               In logical scaling.
1629
/// * `height`  - The height in pixels to resize the window to.
1630
///               In logical scaling.
1631
///
1632
/// # Examples
1633
///
1634
/// ```no_run
1635
/// use cssh_rs_platform_windows::{arrange_console, DefaultWindowsApi};
1636
///
1637
/// let api = DefaultWindowsApi;
1638
/// arrange_console(&api, 100, 100, 800, 600);
1639
/// ```
1640
0
pub fn arrange_console(api: &dyn WindowsApi, x: i32, y: i32, width: i32, height: i32) {
1641
    // FIXME: sometimes a daemon or client console isn't being arrange correctly
1642
    // when this simply retrying doesn't solve the issue. Maybe it has something to do
1643
    // with DPI awareness => https://docs.rs/embed-manifest/latest/embed_manifest/
1644
0
    api.arrange_console(x, y, width, height).unwrap();
1645
0
}
1646
1647
/// Detects if the current windows installation is Windows 10 or not using the provided API.
1648
///
1649
/// Uses the os version, Windows 10 is < `10._.22000`. Windows 11 started with build 22000.
1650
///
1651
/// # Arguments
1652
///
1653
/// * `api` - The Windows API implementation to use.
1654
///
1655
/// # Returns
1656
///
1657
/// Whether the current windows installation is Windows 10 or not.
1658
///
1659
/// # Examples
1660
///
1661
/// ```no_run
1662
/// use cssh_rs_platform_windows::{is_windows_10, DefaultWindowsApi};
1663
///
1664
/// if is_windows_10(&DefaultWindowsApi) {
1665
///     println!("Running on Windows 10");
1666
/// } else {
1667
///     println!("Running on Windows 11 or newer");
1668
/// }
1669
/// ```
1670
10
pub fn is_windows_10(api: &dyn WindowsApi) -> bool {
1671
10
    let version = api.get_os_version();
1672
10
    let mut iter = version.split('.');
1673
10
    let (major, _, build) = (
1674
10
        iter.next().unwrap().parse::<usize>().unwrap(),
1675
10
        iter.next().unwrap().parse::<usize>().unwrap(),
1676
10
        iter.next().unwrap().parse::<usize>().unwrap(),
1677
10
    );
1678
10
    return major < 10 || (
major == 109
&&
build < 220007
);
1679
10
}
1680
1681
#[cfg(test)]
1682
#[path = "tests/test_api.rs"]
1683
mod test_mod;